package org.ssm.cas.casclient.controller;

import org.jasig.cas.client.authentication.AttributePrincipal;
import org.jasig.cas.client.validation.Assertion;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import static org.jasig.cas.client.util.AbstractCasFilter.CONST_CAS_ASSERTION;

/**
 * @author ssm
 */
@Controller
public class LoginController {

    /**
     * cas认证服务中心退出地址
     */
    @Value("${cas-custom.server-logout-url}")
    private String CAS_SERVER_URL_LOGOUT;

    /**
     * 客户端退出成功地址
     */
    @Value("${cas-custom.client-logout-url}")
    private String CLIENT_LOGOUT_URL;

    @ResponseBody
    @RequestMapping("/login")
    public String login(HttpSession session) {
        Assertion assertion = (Assertion) session.getAttribute(CONST_CAS_ASSERTION);
        AttributePrincipal principal = assertion.getPrincipal();
        String name = principal.getName();
        return "sso-user: " + name;
    }

    /**
     * 退出 后自动重定向自定义接口
     * @param request
     * @return
     */
    @RequestMapping("/system/logout")
    public String logout(HttpServletRequest request) {
        HttpSession session = request.getSession();
        session.invalidate();
        return "redirect:" + CAS_SERVER_URL_LOGOUT + "?service=" + CLIENT_LOGOUT_URL;

    }

    /**
     * 退出成功接口
     * @return
     */
    @RequestMapping("/system/logoutSuccess")
    @ResponseBody
    public String logoutSuccess(HttpSession session) {
        Assertion assertion = (Assertion) session.getAttribute(CONST_CAS_ASSERTION);
        return assertion == null? "sso-user成功退出！": "";
    }

}